var jstree = $.tree_create();
$(function() {
	jstree.init($('#tree'), {
		data: {
			type: 'json',
			async: true,
			url: 'tree-node/'
		},
		cookies: {},
		ui: {
			dots: false,
			animation: 250,
			context: false
		},
		rules: {
			deletable: ['category'],
			draggable: ['category'],
			dragrules: [
				//'category inside root',
				'category inside category',
				'category before category',
				'category after category'
			]
		},
		lang: {
			new_node: 'Untitled category',
			loading: ' '
		},
		callback: {
			onrgtclk: function(node, tree_obj, e) {
				e.preventDefault();
			},
			onload: function(tree_obj) {
				$('#tree').find('.no-children').removeClass('open').removeClass('closed');
				if (!$('#tree a.clicked').length) {
					$('#tree a:first').click();
				}
			},
			onchange: function(node, tree_obj) {
				$.get('?id='+node.id, function() {
					if ($(node).attr('rel')=='root') {
						$('a.delete').addClass('disabled');
					} else {
						$('a.delete').removeClass('disabled');
					}
					$('a.save').addClass('disabled');
					//initTinyMce();
				});
			},
			onopen: function(node, tree_obj) {
				$(node).find('.no-children').removeClass('open').removeClass('closed').removeClass('no-children');
			}
			
		}
	});
	
	
	$('a.suspend').livequery('click', function(e) {
		e.preventDefault();
		$.blockUI({ overlayCSS: { opacity: '0.2' }, css: { padding: '15px' } });
		$('.blockMsg').hide();
		$.post('/admin/shop/products/actions/suspend/', { id: $('#id').val() }, function(responseJson) {
			$('a.suspend').parent().addClass('hidden');
			$('a.resume').parent().removeClass('hidden');
			$.unblockUI();
		}, 'json');
	});
	$('a.resume').livequery('click', function(e) {
		e.preventDefault();
		$.blockUI({ overlayCSS: { opacity: '0.2' }, css: { padding: '15px' } });
		$('.blockMsg').hide();
		$.post('/admin/shop/products/actions/resume/', { id: $('#id').val() }, function(responseJson) {
			if (responseJson.ok==true) {
				$('a.resume').parent().addClass('hidden');
				$('a.suspend').parent().removeClass('hidden');
				$.unblockUI();
			} else {
				
			}
		}, 'json');
	});
	$('a.delete').click(function(e) {
		e.preventDefault();
		if (confirm('Are you sure you want to remove this product?')) {
			e.preventDefault();
			$.blockUI({ overlayCSS: { opacity: '0.2' }, css: { padding: '15px' } });
			$('.blockMsg').hide();
			$.post('/admin/shop/products/actions/delete/', { id: $('#id').val() }, function(responseJson) {
				if (responseJson.ok==true) {
					$.unblockUI();
					window.location = responseJson.location;
				} else {

				}
			}, 'json');
		}
	});
	
	$('a.add').click(function(e) {
		e.preventDefault();
		var code = prompt('Enter the new product code:');
		if (code) window.location = '/admin/shop/products/edit/' + code + '/';
	});
	
});